<template>
	<view class="wrapper">
		<view class="" style="text-align: right;font-weight: bold;font-size: 28rpx;" @tap="SelectPopupShow = true">
			{{localesValue}}
			
		</view>
		<view class="header">
			<image class="logo" src="@/static/logo.png"></image>
		</view>
		<view class="login-box">
			<view class="login-mode-line">
				<view class="mode-tip">{{
          showType ? "Sign up with" : $t("login.loginWith")
        }}</view>
				<view class="tab" @click="handleChangeTab(0)">
					<text :class="[activeTab === 0 ? 'activeFont' : '']">{{
            $t("login.Phone")
          }}</text>
					<view class="bottom-line" v-if="!activeTab"></view>
				</view>
				<!-- <view class="tab" @click="handleChangeTab(1)">
					<text :class="[activeTab === 1 ? 'activeFont' : '']">{{
            $t("login.Email")
          }}</text>
					<view class="bottom-line" v-if="activeTab"></view>
				</view> -->
			</view>
			<view class="cell-line">
				<input :placeholder="$t('login.Email')" placeholder-style="color: #A6A6A6;" class="cell-input" v-if="activeTab"
					v-model="email" />
				<view class="input-box" v-else>
					<view class="prefix" @click="openAreaCodePopup">
						{{ AreaPhone }}
						<view class="triangle"> </view>
					</view>
					<input v-model="userPhone" class="email-view" style="font-size: 26upx" maxlength="11"
						placeholder-style="color: #A6A6A6;" :placeholder="$t('user.New-Number')" />
				</view>
			</view>
			<view class="cell-line">
				<input :placeholder="$t('login.CodeText')" placeholder-style="color: #A6A6A6;" class="cell-input"
					v-model="verificationCode" />
				<view v-if="!codeShow" class="code" @click="getCodeHandle">{{
          $t("index.GET")
        }}</view>
				<view v-else>
					<u-count-down :time="60 * 1000" format="ss" @change="onChange" @finish="codeShow = false">
						<view class="count-down">
							<text class="count-down__item">{{ timeData.seconds }}</text>s
						</view>
					</u-count-down>
				</view>
			</view>
			<view v-if="showType">
				<u-button text="Sign up" class="login-btn" @click="handleRegisterOrLogin" :loading="btnLoading"></u-button>
				<view class="change-tip">Already have an account？</view>
				<u-button text="Log in" class="change-btn" @click="handleChangeType"></u-button>
			</view>
			<view v-else>
				<u-button :text="$t('login.Login')" class="login-btn" @click="handleRegisterOrLogin"
					:loading="btnLoading"></u-button>
				<!-- <view class="change-tip">Don't have an account？</view> -->
				<!-- <u-button text="Create account" class="change-btn" @click="handleChangeType"></u-button> -->
				<view class="user-agreement">
					<u-checkbox-group v-model="checkboxValue" placement="column" @change="checkboxChange">
						<u-checkbox size="14" activeColor="#61BDB2" name="userAgree">
						</u-checkbox>
					</u-checkbox-group>
					<text>{{ $t("login.userAgree") }}
						<text style="color: #61bdb2" @click="gotoUserGreen">{{ $t("login.userAgreeGreen") }}</text>
					</text>
				</view>
			</view>
		</view>
		<view v-show="activeTab === 1 && codeShow" class="verification-code-hint" @click="showVerificationCode = true">
			{{ $t("login.emailPostTip") }}
		</view>
		<!-- 选择手机区号弹出框 -->
		<u-popup :show="showAreaCode" @close="showAreaCode = false">
			<view class="area-popup">
				<view class="area-popup__header">
					{{ $t("user.Select-Area-Code") }}
				</view>

				<view class="area-popup__input">
					<u-input v-model="searchValue" shape="circle" :placeholder="$t('feeServices.search')" prefixIcon="search"
						prefixIconStyle="font-size: 40rpx;color: #878787" placeholderStyle="{
							color: '#878787',
							fontSize:'26rpx'
						}">
					</u-input>
					<view class="area-popup__input__btn" @click="closePopup">
						{{ $t("index.Cancel") }}
					</view>
				</view>

				<view class="area-popup__container">
					<scroll-view scroll-top="0" scroll-y="true" class="scroll-Y" :scroll-into-view="scrollIntoView">
						<view v-for="(item, index) in filterAreasList" :key="index">
							<view :id="'s-' + filterAreasList[index].en.slice(0, 1)" class="scroll-view-letter" v-if="
                  index == 0 ||
                  filterAreasList[index].en.slice(0, 1) !==
                    filterAreasList[index - 1].en.slice(0, 1)
                ">{{ filterAreasList[index].en.slice(0, 1) }}</view>
							<view class="scroll-view-item" @click="selectAreaPhone(item)">
								<text>{{ locale == 'zh-Hans'? item.cn : item.en }}</text>
								<text>{{ item.code }}</text>
							</view>
						</view>
					</scroll-view>

					<!-- 右侧导航栏 -->
					<view class="suspension-frame" v-if="filterAreasList.length !== 0">
						<view class="text" v-for="(item, index) in filterAreasList" :key="index" v-if="
                index == 0 ||
                filterAreasList[index].en.slice(0, 1) !==
                  filterAreasList[index - 1].en.slice(0, 1)
              " :class="{ active: currentView == item.en.slice(0, 1) }" @click="onLocation(item)">
							{{ filterAreasList[index].en.slice(0, 1) }}
						</view>
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 验证码弹窗提示 -->
		<u-popup @close="showVerificationCode = false" :show="showVerificationCode" mode="center" :round="100"
			class="showVerificationCode-box">
			<view class="showVerificationCode-container">
				<view class="VerificationCode-icon">
					<img src="../../static/image/tips.png" alt="" />
				</view>
				<view class="VerificationCode-top">{{ $t("login.emailPopUp1") }}</view>
				<view class="VerificationCode-center">{{
          $t("login.emailPopUp2")
        }}</view>
				<view class="confirm-ok">
					<text @click="showVerificationCode = false">{{ $t('Ok') }}</text>
				</view>
			</view>
		</u-popup>
		<SelectPopup :show.sync="SelectPopupShow" :option="locales" :title="$t('user.language')" :value="applicationLocale"
			@finish="onChangeLocal" v-if="SelectPopupShow" labelSigned="text" valueSigned="code"></SelectPopup>
	</view>
</template>

<script>
	import SelectPopup from "@/components/SelectPopup.vue";
	import {
		changeLang
	} from '@/utils/olImInterface.js'
	import {
		sendSms
	} from "@/utils/index";
	import {
		mapActions
	} from "vuex";
	import areasList from "@/utils/GlobalPhonePrefix.js";
	import {
		queryUserPhoneRegister,
		querySmsLogin,
		queryEmailRegister,
		queryEmailLogin,
		querySendSms,
		querySendMail
	} from "@/services/login";
	import checkPhoneByCountry from '@/utils/checkPhoneByCountry.js'
import {
		queryChangeip
	} from "@/services/login";
	export default {
		name: "Login",
		data() {
			return {
				userAgree: false, // 用户协议
				checkboxValue: [], // 勾选用户协议
				codeShow: false,
				areasList,
				AreaPhone: "+7",
				email: "",
				userPhone: "",
				verificationCode: "", // 固定验证码
				activeBtn: false,
				loading: false,
				showType: 0, // 0 登录 1 注册
				activeTab: 0, // 0 phone 1 Email
				codeText: "GET",
				btnLoading: false,
				showAreaCode: false,
				showVerificationCode: false, // 验证码提示框
				searchValue: "",
				scrollIntoView: "",
				currentView: "",
				timeData: {},
				locale: '',
				SelectPopupShow:false
			};
		},
		components:{SelectPopup},
		computed: {
			filterAreasList() {
				if (
					this.searchValue == "" ||
					this.searchValue == undefined ||
					this.searchValue == null
				) {
					let arr = this.areasList.filter((item) => {
						return item.en === "China" || item.en === "Russia";
					});
					this.currentView = arr.length > 0 ? arr[0].en.slice(0, 1) : "";
					return arr;
				} else {
					let arr = this.areasList.filter(
						(t) =>
						t.en.toLowerCase().indexOf(this.searchValue.toLowerCase()) !== -1 &&
						(t.en === "China" || t.en === "Russia")
					);
					this.currentView = arr.length > 0 ? arr[0].en.slice(0, 1) : "";
					return arr;
				}
			},
		},
		onLoad() {
			this.change_local()
		},
		methods: {
			change_local(){
				queryChangeip().then(res=>{
					console.log(res)
					if(res.result.data==='中国'){
						this.onLocaleChange('zh-Hans');
						changeLang()
					}
				})
			},
			// 切换语言
			onChangeLocal(value) {
				this.onLocaleChange(value);
				changeLang()
				console.log("语言切换为", value);
			},
			handleBlur() {
				if (this.AreaPhone.replace(/\+/g, "") == 7) {
					if (this.userPhone && !checkPhoneByCountry(this.userPhone, 'ru-RU')) {
						uni.showToast({
							title: this.$t("login.phone-error"),
							icon: "none",
							duration: 2000,
						});
						return false
					}
					return true
				} else if (this.AreaPhone.replace(/\+/g, "") == 86) {
					if (this.userPhone && !checkPhoneByCountry(this.userPhone, 'zh-CN')) {
						uni.showToast({
							title: this.$t("login.phone-error"),
							icon: "none",
							duration: 2000,
						});
						return false
					}
					return true
				}
			},
			checkboxChange(n) {
				// 长度大于0表示已经勾选用户协议
				if (n.length > 0) {
					this.userAgree = true;
				} else {
					this.userAgree = false;
				}
			},
			...mapActions(["changeToken", "changeRongToken"]),
			// 切换登录/注册
			handleChangeType() {
				this.showType = !this.showType;
			},
			onChange(e) {
				this.timeData = e;
			},
			openAreaCodePopup() {
				this.showAreaCode = true;
			},
			closePopup() {
				this.searchValue = "";
				this.showAreaCode = false;
			},
			selectAreaPhone(value) {
				this.AreaPhone = value.code;
				this.searchValue = "";
				this.showAreaCode = false;
			},
			async getCodeHandle() {
				if (Number(this.activeTab) === 0) {
					if (!this.handleBlur()) {
						return
					}
					if (!this.userPhone || this.userPhone.length === 0) {

						uni.showToast({
							title: this.$t("login.phoneError"),
							icon: "none",
							duration: 2000,
						});
						return
					}
					const resp = await querySendSms({
						phone: this.userPhone,
						areaCode: this.AreaPhone.replace("/+/g", "")
					});
					if (!resp.success) return;
					this.codeShow = true;
					uni.showToast({
						title: this.$t("index.Sentsuccessfully"),
						icon: "none",
						duration: 1500,
					});
				} else if (Number(this.activeTab) === 1) {
					if (!this.email || this.email.length === 0) {
						uni.showToast({
							title: this.$t("login.emailError"),
							icon: "none",
							duration: 2000,
						});
						return
					}
					const resp = await querySendMail({
						mail: this.email
					})
					if (!resp.success) return;
					this.codeShow = true;
					uni.showToast({
						title: this.$t("index.Sentsuccessfully"),
						icon: "none",
						duration: 1500,
					});
				}
			},
			// 切换邮箱/手机号
			handleChangeTab(tab) {
				if (this.activeTab === tab) return;
				this.activeTab = tab;
				this.codeShow = false;
				this.showVerificationCode = false
			},
			// 点击登录/注册按钮
			handleRegisterOrLogin() {
				if (!this.userAgree) {
					uni.showToast({
						title: this.$t("login.needAgree"),
						icon: "none",
						duration: 2000,
					});
					return;
				}
				if (!this.handleBlur()) {
					return
				}
				if (this.showType && !this.activeTab) {
					if (!this.userPhone || this.userPhone.length === 0) {
						uni.showToast({
							title: this.$t("login.phoneError"),
							icon: "none",
							duration: 2000,
						});
						return
					}
					if (!this.verificationCode || this.verificationCode.length === 0) {
						uni.showToast({
							title: this.$t("login.codeError"),
							icon: "none",
							duration: 2000,
						});
						return
					}
					// 手机号注册
					this.btnLoading = true;
					this.handleUserPhoneRegister();
				} else if (this.showType && this.activeTab) {
					if (!this.email || this.email.length === 0) {
						uni.showToast({
							title: this.$t("login.emailError"),
							icon: "none",
							duration: 2000,
						});
						return
					}
					if (!this.verificationCode || this.verificationCode.length === 0) {
						uni.showToast({
							title: this.$t("login.codeError"),
							icon: "none",
							duration: 2000,
						});
						return
					}
					// 邮箱注册
					this.btnLoading = true;
					this.handleEmailRegister();
				} else if (!this.showType && !this.activeTab) {
					if (!this.userPhone || this.userPhone.length === 0) {
						uni.showToast({
							title: this.$t("login.phoneError"),
							icon: "none",
							duration: 2000,
						});
						return
					}
					if (!this.verificationCode || this.verificationCode.length === 0) {
						uni.showToast({
							title: this.$t("login.codeError"),
							icon: "none",
							duration: 2000,
						});
						return
					}
					// 手机号登录
					this.btnLoading = true;
					this.handleSmsLogin();
				} else if (!this.showType && this.activeTab) {
					if (!this.email || this.email.length === 0) {
						uni.showToast({
							title: this.$t("login.emailError"),
							icon: "none",
							duration: 2000,
						});
						return
					}
					if (!this.verificationCode || this.verificationCode.length === 0) {
						uni.showToast({
							title: this.$t("login.codeError"),
							icon: "none",
							duration: 2000,
						});
						return
					}
					// 邮箱登录
					this.btnLoading = true;
					this.handleEmailLogin();
				}
			},
			// 手机号注册
			async handleUserPhoneRegister() {
				const resp = await queryUserPhoneRegister({
					userPhone: this.userPhone,
					smsCode: this.verificationCode,
				});
				console.log("queryUserPhoneRegister", resp);
				this.btnLoading = false;
				if (!resp.success) return;
				this.handleChangeType();
			},
			// 邮箱注册
			async handleEmailRegister() {
				const resp = await queryEmailRegister({
					email: this.email,
					emailCode: this.verificationCode,
				});
				console.log("queryEmailRegister", resp);
				this.btnLoading = false;
				if (!resp.success) return;
				this.handleChangeType();
			},
			// 手机号登录
			async handleSmsLogin() {
				console.log(11114444, this.AreaPhone);
				const resp = await querySmsLogin({
					userPhone: this.userPhone,
					smsCode: this.verificationCode,
					userType: "app_user",
					internationalAreaCode: this.AreaPhone.replace(/\+/g, ""),
				});
				console.log("querySmsLogin", resp);
				this.btnLoading = false;
				if (!resp.success) return;
				this.changeToken(resp.result.data.token);
				this.changeRongToken(resp.result.data.rongToken);
				if (resp.result.data.token) {
					this.getModuleGroupList()
				}
				uni.reLaunch({
					url: "/pages/chat/Chat",
				});
			},
			// 邮箱验证登录
			async handleEmailLogin() {
				const resp = await queryEmailLogin({
					email: this.email,
					emailCode: this.verificationCode,
				});
				console.log("queryEmailLogin", resp);
				this.btnLoading = false;
				if (!resp.success) return;
				this.changeToken(resp.result.data.token);
				this.changeRongToken(resp.result.data.rongToken);
				if (resp.result.data.token) {
					this.getModuleGroupList()
				}
				uni.reLaunch({
					url: "/pages/chat/Chat",
				});
			},
			onLocation(value) {
				this.scrollIntoView = "s-" + value.en.slice(0, 1);
				this.currentView = value.en.slice(0, 1);
				console.log(value);
			},
		},
		onShow() {
			this.currentView = this.areasList[0]?.en?.slice(0, 1);
			this.locale = uni.getLocale()
		},
		onBackPress(event) {
			uni.reLaunch({
				url: '/pages/chat/Chat'
			});
			return true;
		},
	};
</script>

<style lang="scss" scoped>
	/deep/ .u-popup__content {
		background: #f6f6f6;
		border-radius: 50upx 50upx 0upx 0upx;
	}

	.wrapper {
		.showVerificationCode-container {
			width: 560upx;
			height: 394upx;
			background: #ffffff;
			font-size: 24upx;
			border-radius: 50upx;
			font-family: Source Han Sans CN;
			font-weight: 400;
			color: #878787;
			line-height: 32upx;

			.VerificationCode-icon {
				height: 140upx;
				text-align: center;
				line-height: 140upx;

				img {
					width: 50upx;
					height: 50upx;
				}
			}

			.VerificationCode-top {
				padding-left: 39upx;
				padding-right: 70upx;
				margin-bottom: 30upx;
			}

			.VerificationCode-center {
				padding-left: 39upx;
				padding-right: 31upx;
				margin-bottom: 40upx;
			}

			// OK
			.confirm-ok {
				font-size: 26upx;
				font-family: Source Han Sans CN;
				font-weight: 500;
				color: #61bdb2;
				text-align: center;
			}
		}

		// 用户协议
		.user-agreement {
			margin-top: 52upx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 24upx;
			font-family: Source Han Sans CN;
			font-weight: 400;
			color: #a6a6a6;
		}

		box-sizing: border-box;
		padding: 0 40upx 40upx;

		.header {
			text-align: center;

			.logo {
				width: 240upx;
				height: 246upx;
			}
		}

		.login-box {
			margin-top: 110upx;
			width: 100%;
			background: #ffffff;
			border-radius: 20upx;
			box-sizing: border-box;
			padding: 60upx 50upx 90upx;
			margin-bottom: 35upx;

			.login-mode-line {
				margin-bottom: 80upx;
				display: flex;
				align-items: center;

				.mode-tip {
					flex: 1;
					// font-size: 24upx;
					font-size: 28upx;
					font-weight: bold;
					font-family: Source Han Sans CN;
					color: #212121;
				}

				.tab {
					position: relative;
					margin-left: 80upx;
					font-size: 30upx;
					font-weight: 400;
					color: #000000;

					.bottom-line {
						position: absolute;
						margin-top: 15upx;
						width: 40upx;
						height: 6upx;
						background: #61bdb2;
						border-radius: 3upx;
						left: 50%;
						transform: translateX(-50%);
					}

					.activeFont {
						color: #61bdb2;
					}
				}
			}

			.cell-line {
				margin-top: 40upx;
				padding: 35upx;
				background: #f6f6f6;
				border-radius: 20upx;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.cell-input {
					width: 85%;
					font-size: 26upx;
					font-weight: 400;
					color: #212121;
					box-sizing: border-box;
				}

				.get-btn {
					font-size: 26upx;
					font-weight: 400;
					color: #61bdb2;
					padding: 0 36upx;
					height: 94upx;
					line-height: 94upx;
				}
			}

			.login-btn {
				margin-top: 80upx;
				width: 100%;
				height: 90upx;
				background: #61bdb2;
				border-radius: 20upx;
				font-size: 30upx;
				font-weight: 400;
				color: #fffefe;
			}

			.change-tip {
				margin-top: 120upx;
				font-size: 26upx;
				font-weight: 400;
				color: #a6a6a6;
				text-align: center;
			}

			.change-btn {
				margin-top: 30upx;
				width: 100%;
				height: 90upx;
				background: #ffffff;
				border: 2upx solid #61bdb2;
				border-radius: 20upx;
				font-size: 30upx;
				font-weight: 400;
				color: #61bdb2;
			}
		}

		// 没有收到验证码点击提示文本的样式
		.verification-code-hint {
			font-size: 24upx;
			font-family: Source Han Sans CN;
			font-weight: 400;
			color: #fe6600;
			text-align: center;
			text-decoration: underline;
		}
	}

	.input-box {
		display: flex;
		align-items: center;

		.prefix {
			display: flex;
			align-items: center;
			justify-content: space-around;
			width: 160rpx;
			border-right: 2rpx solid #f6f6f6;
			font-size: 30rpx;
			font-weight: 600;

			.triangle {
				width: 0;
				height: 0;
				border-top: 12rpx solid #000000;
				border-right: 10rpx solid transparent;
				border-left: 10rpx solid transparent;
				border-radius: 4rpx 4rpx 0 0;
				margin-right: 20rpx;
				margin-top: 6upx;
			}
		}
	}

	.area-popup {
		position: relative;
		height: 80vh;
		background: #f6f6f6;
		border-radius: 50rpx 50rpx 0px 0px;
		padding: 42rpx 0;

		&__header {
			font-size: 34rpx;
			font-family: Source Han Sans CN;
			font-weight: 500;
			text-align: center;
			color: #000000;
			margin-bottom: 40rpx;
		}

		&__input {
			display: flex;
			align-items: center;
			padding: 0 30rpx;
			margin-bottom: 10rpx;

			/deep/ .u-input--circle {
				border-radius: 100px;
				background: #fff;
				border: 0;
				padding: 26rpx 30rpx;
			}

			&__btn {
				font-size: 26rpx;
				color: #4eafa3;
				margin-left: 30rpx;
			}
		}

		&__container {
			position: relative;

			.scroll-Y {
				height: calc(90vh - 128rpx);

				.scroll-view-letter {
					height: 66rpx;
					line-height: 66rpx;
					padding: 0 30rpx;
					background-color: #f6f6f6;
					color: #878787;
				}

				.scroll-view-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					height: 110rpx;
					padding: 0 76rpx 0 30rpx;
					background-color: #ffffff;
					font-size: 30rpx;
					color: #000000;
				}
			}
		}

		.suspension-frame {
			position: absolute;
			top: 50%;
			transform: translateY(-50%);
			right: 20upx;
			width: 40upx;
			background: rgba($color: #000000, $alpha: 0.4);
			border-radius: 20upx;
			box-sizing: border-box;
			padding: 12upx 0;
			text-align: center;

			.text {
				font-size: 22upx;
				font-weight: 400;
				color: #ffffff;
				margin: 6upx 0;

				&.active {
					margin: 6rpx auto;
					width: 34upx;
					// height: 34upx;
					background: #61bdb2;
					border-radius: 17upx;
				}
			}
		}
	}

	.code-views {
		border-top: 2upx solid #f6f6f6;
		padding: 44upx 0upx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.code {
		font-size: 30upx;
		font-weight: 400;
		color: #61bdb2;
	}

	.count-down {
		font-size: 30rpx;
		font-weight: 400;
		color: #61bdb2;
	}

	.Change {
		width: 100%;
		height: 90upx;
		background: #61bdb2;
		border-radius: 20upx;
		font-size: 30upx;
		font-weight: 500;
		color: #ffffff;
		margin-top: 80upx;
		text-align: center;
		line-height: 90upx;
	}
</style>